package com.example.servlet;

import com.example.dao.StudentDao;
import com.example.entity.Student;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    // 依赖注入,强耦合
    private StudentDao studentDao = new StudentDao();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取表单数据
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String remember = request.getParameter("remember");

        System.out.println(username);
        System.out.println(email);
        System.out.println(remember);
        
        // 验证输入数据
        if (username == null || username.trim().isEmpty()) {
            request.setAttribute("error", "用户名不能为空！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        
        if (email == null || email.trim().isEmpty()) {
            request.setAttribute("error", "邮箱不能为空！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        
        // 验证用户名长度
        if (username.length() < 2 || username.length() > 20) {
            request.setAttribute("error", "用户名长度必须在2-20个字符之间！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        
        // 验证邮箱格式
        if (!email.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
            request.setAttribute("error", "邮箱格式不正确！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        
        // 查询数据库验证用户
        Student student = studentDao.validateStudent(username, email);


        if (student != null) {

            // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute("student", student.getName());
            // 在登录成功后

            session.setAttribute("studentId", student.getId());
            System.out.println("Set student ID in session: " + student.getId());

            // 如果选择了自动登录
            if (remember != null && !remember.isEmpty()) {
                Cookie nameCookie = new Cookie("username", username);
                Cookie emailCookie = new Cookie("email", email);

                // 设置cookie有效期（天数）
                int days = Integer.parseInt(remember);
                nameCookie.setMaxAge(days * 24 * 60 * 60);
                emailCookie.setMaxAge(days * 24 * 60 * 60);
                System.out.println("免密码登录days="+days);
                response.addCookie(nameCookie);
                response.addCookie(emailCookie);
            }

            response.sendRedirect("index.jsp");
        } else {
            request.setAttribute("error", "用户名或邮箱错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }


        /*
        if (student != null) {
            // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute("student", student);
            
            // 如果选择了"记住我"
            if ("on".equals(remember)) {
                session.setMaxInactiveInterval(7 * 24 * 60 * 60); // 设置session有效期为7天
            }
            
            // 重定向到主页
            response.sendRedirect("index.jsp");
        } else {
            // 登录失败
            request.setAttribute("error", "用户名或邮箱错误！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }*/
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // GET请求直接转发到登录页面
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }
} 